<template>
    <div class="main_container">
        <Modal v-model="active" title="用户信息修改" @on-ok="handleSubmit('changeData')" @on-cancel="handleCancel">
            <Form ref="changeData" :model="changeData" :rules="userRule" :label-width="80" :label-colon="true">
                <FormItem label="用户名" prop="username">
                    <Input v-model="changeData.username" :disabled="!isCreate" />
                </FormItem>
                <FormItem label="密码" prop="password">
                    <Input v-model="changeData.password" :disabled="!isCreate" />
                    <Button long type="error" shape="circle" v-show="!isCreate" @click="changeData.password = '123456'"
                        style="margin-top: 10px;">重置密码</Button>
                </FormItem>
                <FormItem label="用户头像">
                    <Avatar :src="changeData.avatar"></Avatar>
                    <Input v-model="changeData.avatar" style="width: 365px;margin-left: 10px;" placeholder="请输入url"
                        type="url" :disabled="!isCreate" />
                    <Button long type="error" shape="circle" @click="changeData.avatar = ''" style="margin-top: 10px;"
                        v-show="!isCreate">是否删除头像（头像违规）</Button>
                </FormItem>
                <FormItem label="角色管理" v-if="!isCreate">
                    <Tag v-for="role in changeData.roleList " closable size="large" @on-close="handleRoleDelete(role)">{{
                        roleMap[role] }}</Tag>
                    <Button icon="ios-add" type="dashed" size="small" @click="handleRoleOpen">添加</Button>
                </FormItem>
                <Modal title="添加角色" v-model="roleAddData.active" @on-ok="handleRoleSubmit">
                    <Select v-model="roleAddData.value">
                        <Option v-for="id in avaliableRoles" :value="id">{{ roleMap[id] }}</Option>
                    </Select>
                </Modal>
            </Form>
        </Modal>
        <Row>
            <Button type="success" @click="handleCreate" size="large" style="margin-left: 70%;width: 200px;" shape="circle">
                添加员工</Button>
        </Row>
        <div class="user_container">
            <List class="list_container">
                <ListItem v-for="user in userData">
                    <ListItemMeta :avatar="user.avatar" :title="user.username" :description="user.password">
                    </ListItemMeta>
                    <Tag v-for="role in user.roleList">{{ roleMap[role] }}</Tag>
                    <template #action>
                        <Space>
                            <Button type="primary" @click="handleUpdate(user)" shape="circle" size="large"
                                style="width:100px">修改</Button>
                            <Button type="error" @click="handleDelete(user.id)" shape="circle" size="large"
                                style="width:100px">删除</Button>
                        </Space>
                    </template>
                </ListItem>
            </List>
        </div>
    </div>
</template>
<script>
import { Avatar, Button, FormItem, Upload } from 'view-ui-plus';

export default {
    name: "Exploit",
    data() {
        return {
            userData: {},
            changeData: {},
            active: false,
            isCreate: false,
            roleMap: {},
            roleAddData: {
                active: false,
                value: "",
            },
            avaliableRoles: [],//缓存可用角色id
            userRule: {
                username: [
                    { required: true, message: '请输入用户名。', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码。', trigger: 'blur' },
                    { type: 'string', min: 4, message: '密码长度大于4位', trigger: 'blur' }
                ]
            },
        };
    },
    methods: {
        renew() {
            this.$api.get("admin/user/list").then((res) => {
                this.userData = res.data.data;
                for (var i in this.userData)
                    this.userData[i].roleList = this.userData[i].roles.split(',');
            });
        },
        handleCreate() {
            this.active = true;
            this.isCreate = true;
            this.changeData = {};
            this.renewAvaliableRoles();//更新可用角色id值
        },
        handleUpdate(user) {
            this.active = true;
            this.isCreate = false;
            this.changeData = user;
            this.renewAvaliableRoles();//更新可用角色id值
        },
        handleDelete(id) {
            console.log("delete: " + id);
            this.$Modal.confirm({
                title: "确认框",
                content: "确认删除该用户吗？",
                onOk: () => {
                    this.$api.post("admin/user/delete/" + id).then((res) => {
                        this.$Notice.info({
                            title: "提示",
                            desc: res.msg,
                        });
                        this.renew();
                    });
                },
            });
        },
        handleSubmit(name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    var url = this.isCreate ? "admin/user/create" : "admin/user/update";
                    this.$api.post(url, this.changeData).then((res) => {
                        this.info(res.msg);
                        this.$refs[name].resetFields();
                        this.renew();
                    })
                }
                else {
                    this.info("失败")
                    this.$refs[name].resetFields();
                }
            })
        },
        handleCancel() {
            this.renew();
        },
        handleRoleDelete(role_id) {
            // this.info("删除" + role_id);
            var data = {
                user_id: this.changeData.id,
                role_id: role_id,
            };
            // console.log(data);
            this.$api.post("admin/role/revoke", data).then((res) => {
                this.info(res.msg);
                if (res.code == 0) {//修改成功
                    this.changeData.roleList = this.changeData.roleList.
                        filter((role) => { return data.role_id != role });//删除角色名
                    this.avaliableRoles.push(role_id);
                }
                else this.renew();//出现未知情况更新
            })
        },
        handleRoleOpen() {//打开角色添加界面
            this.roleAddData.active = true;
            this.roleAddData.value = "";
        },
        handleRoleSubmit() {//提交角色数据
            var data = {
                user_id: this.changeData.id,
                role_id: this.roleAddData.value
            };
            this.$api.post("admin/role/grant", data).then((res) => {
                this.info(res.msg);
                this.changeData.roleList.push(this.roleAddData.value);
                this.avaliableRoles = this.avaliableRoles.filter((role) => { return role != data.role_id })
            })
        },
        renewAvaliableRoles() {
            //  return [];
            this.avaliableRoles = Object.keys(this.roleMap);
            // console.log("更新可利用角色数据");
            if (this.changeData == null) {
                this.avaliableRoles = this.avaliableRoles.filter((value) => {
                    for (var i of this.changeData.roleList)
                        if (i == value) return false;
                    return true;
                });
            }
            console.log(this.avaliableRoles)
        },
        info(message) {
            this.$Notice.info({
                title: "提示",
                desc: message,
            })
        }
    },
    created() {
        this.$api.get("admin/role/map").then((res) => {
            this.roleMap = res.data.data;//获得身份(id, name)键值对
            this.renew();
        })
    },
    components: { FormItem, Avatar, Upload, Button }
}
</script>
<style scoped>
.main_container {
    width: 90%;
    height: 90%;
    border-radius: 10px;
    padding: 20px 10px;
    border: solid;
    margin: auto;
    margin-top: 20px;
}

.user_container {
    height: 460px;
    overflow: auto;
}

.list_container {
    padding: 0 50px;
}
</style>